import AMapLoader from '@amap/amap-jsapi-loader'
import { AMAP_MAP_KEY, AMAP_MAP_SECURITY_KEY } from '@/utils/constant'

type Newable = (arg: any) => void

export interface MapOptions {
  center?: [number, number] // 初始地图中心经纬度
  zoom?: number //初始地图缩放级别
  zooms?: [number, number] // 缩放级别范围 取值范围 [2 ~ 26] 默认为 [2, 20]
  rotation?: number // 地图顺时针旋转的角度 [0-360] 默认值：0
  viewMode?: '2D' | '3D' // 地图类型 默认为 2D ，可选 3D
  mapStyle?: string // 地图的显示样式 https://lbs.amap.com/api/javascript-api-v2/documentation#mapstyle
  manual?: boolean // 手动加载
  features?: string[] // 地图上显示的元素种类, ['bg','point','road','building']
  animateEnable?: boolean // 是否开启平移动画
  pluginsOption?: Record<string, (arg: Newable) => any>
}

const defaultMapOptions: MapOptions = {
  center: [105.602725, 37.076636],
  zoom: 4,
  zooms: [2, 22],
  rotation: 0,
  manual: false,
  viewMode: '3D',
  features: ['bg', 'road', 'point'],
  animateEnable: false,
  pluginsOption: { ToolBar: plugin => new plugin({ position: 'RB' }) }
}
// 可定制化插件
const customizablePlugins = ['AMap.ToolBar', 'AMap.Scale']

export const useMap = (div: string | HTMLDivElement, mapOptions: MapOptions = defaultMapOptions) => {
  const AMap = ref()
  const map = ref()
  // 合并配置项
  const mergedOptions = { ...defaultMapOptions, ...mapOptions }

  async function initMap() {
    try {
      window._AMapSecurityConfig = {
        securityJsCode: AMAP_MAP_SECURITY_KEY
      }

      AMap.value = await AMapLoader.load({
        key: AMAP_MAP_KEY,
        version: '2.0',
        plugins: [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.MapType',
          'AMap.PlaceSearch',
          'AMap.Geocoder',
          'AMap.MouseTool',
          'AMap.RectangleEditor',
          'AMap.CircleEditor',
          'AMap.PolygonEditor',
          'AMap.DistrictSearch',
          'AMap.MarkerCluster',
          'AMap.MoveAnimation'
        ] // 插件列表
      })

      map.value = new AMap.value.Map(div, mergedOptions)
      const { pluginsOption = {} } = mergedOptions

      //异步加载插件
      AMap.value.plugin(customizablePlugins, function () {
        customizablePlugins.forEach(key => {
          const pluginsName = key.replaceAll('AMap.', '')
          const customOptions = pluginsOption[pluginsName]
          map.value.addControl(customOptions ? customOptions(AMap.value[pluginsName]) : new AMap.value[pluginsName]())
        })
        // // 工具条，控制地图的缩放、平移等
        // map.value.addControl(new AMap.value.ToolBar())
        // // 比例尺，显示当前地图中心的比例尺
        // map.value.addControl(new AMap.value.Scale())
      })
    } catch (error) {
      console.log('高德地图加载出错', error)
    }
  }

  function destroyMap() {
    map.value && map.value.destroy()
  }

  onMounted(() => {
    // dialog 中使用 onMounted 元素未创建
    // 需要阻止自动创建
    if (!mergedOptions.manual) initMap()
  })

  onUnmounted(() => {
    destroyMap()
  })

  return {
    map,
    AMap,
    initMap,
    destroyMap
  }
}
